#include "cworker_redis.h"

static redisContext *conn = NULL;

int cworker_redis_init(cworker_redis_cfg_t *cfg) {
    int ret = -1;
    redisReply *reply = NULL;

    char *hostname = wtk_string_to_str(&(cfg->host));
    log_i("Connecting to Redis: %s:%d, db: %d", hostname, cfg->port, cfg->db);

    conn = redisConnect(hostname, cfg->port);
    if (conn == NULL || conn->err) {
        if (conn) {
            log_e("Connection error: %s, host: %s, port: %d", conn->errstr, hostname, cfg->port);
            redisFree(conn);
        } else {
            log_e0("Connection error: can't allocate redis context");
        }

        goto end;
    }

    if (cfg->password.len > 0) {
        reply = redisCommand(conn, "AUTH %s", wtk_string_to_str(&(cfg->password)));
        log_i("AUTH: %s", reply->str);
    }

    if (cfg->db > 0) {
        reply = redisCommand(conn, "SELECT %d", cfg->db);
    }

    log_i0("Redis connected.");

    ret = 0;

end:
    if (reply)
        freeReplyObject(reply);

    return ret;
}

void cworker_redis_finit() {
    if (conn)
        redisFree(conn);
}

cJSON * cworker_redis_blpop(char *list_key, int timeout) {
    redisReply *reply = NULL;
    cJSON *ret = NULL;

    reply = redisCommand(conn,"BLPOP %s %d", list_key, timeout);
    if (reply) {
        log_i("key: %s, value: %s", reply->element[0]->str, reply->element[1]->str);
        ret = cJSON_Parse(reply->element[1]->str);
        freeReplyObject(reply);
    } else {
        log_w0("reply null.");
    }

    return ret;
}

cJSON * cworker_redis_hget(char *dict_key) {
    cJSON *ret = NULL;
    return ret;
}
